package com.letv.app.ljodfh.ui.fragment;


import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.letv.app.ljodfh.R;
import com.letv.app.ljodfh.beans.ChatItem;
import com.letv.app.ljodfh.http.AbsListNetCallback;
import com.letv.app.ljodfh.http.NetUtils;
import com.letv.app.ljodfh.ui.adapter.ChatRoomAdapter;
import com.letv.app.ljodfh.ui.util.RBaseItemDecoration;
import com.letv.app.ljodfh.utils.ListTypeUtils;

import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 聊天室的fragment
 */
public class ChatRoomFragment extends LivingChildFragment<ChatItem> {

    public static final int MODE_COMMENT = 551;

    @BindView(R.id.rv_chat_room)
    protected RecyclerView mRecyclerView;

    private LinearLayoutManager mLLManager;
    private ChatRoomAdapter mAdapter;
    private long adapterRefreshTime;

    private boolean mIsLoading = false;
    private int mPageNo = 0;
    private int mPageAll;
    private boolean isFirtShowing = false;

    private boolean shouldCallFresh;
    private Comparator<ChatItem> dyComparator=new Comparator<ChatItem>() {
        @Override
        public int compare(ChatItem o1, ChatItem o2) {
            if (o1!=null && o2!=null){
                if (isLiving) {
                    return DateUtils.getDataDate(o2).compareTo(DateUtils.getDataDate(o1));
                }else {
                    return DateUtils.getDataDate(o1).compareTo(DateUtils.getDataDate(o2));
                }
            }
            return 0;
        }
    };
    public ChatRoomFragment() {
        // Required empty public constructor
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_chat_room, container, false);
        ButterKnife.bind(this, view);
        return view;
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        super.onViewCreated(view, savedInstanceState);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mLLManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLLManager);
        mRecyclerView.addItemDecoration(new RBaseItemDecoration(1));
        if (shouldCallFresh) {
            shouldCallFresh = false;
            onRefresh();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(baseLiveId)) {
            if (hasCreated) {
                onRefresh();
            } else {
                shouldCallFresh = true;
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            refreshShowing();
        }
    }

    @Override
    public boolean canScrollUp(MotionEvent e) {
        JLog.e("sdad  in up");
        boolean b = ViewCompat.canScrollVertically(mRecyclerView, -1);
        return b;
    }

    @Override
    public boolean canScrollDown(MotionEvent e) {
        JLog.e("sdad  in down");
        boolean b = ViewCompat.canScrollVertically(mRecyclerView, 1);
        return b;
    }

    @OnClick(value = R.id.chat_room_comment)
    public void commentClick(View v) {
        if (netCallback != null) {
            netCallback.onNetPrepare(this, MODE_COMMENT);
        }
    }

    public void getData() {
        if (netCallback != null) {
            netCallback.onNetPrepare(this, 0);
        }
        NetUtils.getNetAdapter().getLiveChatList(getOwnerName(), baseLiveId, new AbsListNetCallback<ChatItem>(ListTypeUtils.ChatItem()) {
            @Override
            public void onSuc(List<ChatItem> chatItems) {
                if (!ListUtils.isListValued(chatItems)) {
                    onError(null, null);
                    return;
                }

                if (mPageAll == 0) {
                    mPageAll = getPageResponse().getData().getPageAll();
                }
                initData(chatItems);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });

    }

    private void initData(final List<ChatItem> list) {
        if (mAdapter == null) {
            mAdapter = new ChatRoomAdapter(getContext(), list);
            mRecyclerView.setAdapter(mAdapter);
        }
        if (mPageNo == 0) {
            mAdapter.setDatas(list);
        } else {
            mAdapter.addDatas(list);
        }
//        int count = mAdapter.getItemCount();
//        if (count > 0) {
//            mRecyclerView.smoothScrollToPosition(count - 1);
//        }
//        new Timer().schedule(new TimerTask() {
//            @Override
//            public void run() {
//
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        mAdapter.addDatas(list);
//                    }
//                });
//            }
//        }, 5000, 5000);
        mPageNo++;
        adapterRefreshTime = SystemClock.elapsedRealtime();
    }

    private synchronized void refreshShowing() {
        if (mAdapter != null) {
            long er = SystemClock.elapsedRealtime();
            if (er - adapterRefreshTime > 1000) {//刷新间隔大于1秒才进行刷新
                int start = mLLManager.findFirstVisibleItemPosition();
                mAdapter.notifyItemRangeChanged(start, mLLManager.findLastVisibleItemPosition() - start + 1);
            }
            adapterRefreshTime = er;
        }
    }

    public void onLoadMore() {
        getData();
    }

    public void onRefresh() {
        if (mIsLoading || isFirtShowing) {
            return;
        }
        mPageNo = 0;
        mIsLoading = true;
        getData();
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
//        ((LivingActivity) getActivity()).onNetFinish(canLoadMore());
        if (netCallback != null) {
            netCallback.onNetEnd(this, 0, canLoadMore());
        }
    }

    public boolean canLoadMore() {
        return mPageNo >= mPageAll ? false : true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (isFirtShowing && !mIsLoading) {
                getData();
            }
            isFirtShowing = false;
        }
    }

    @Override
    public void addDatas(List<ChatItem> list, int mode) {
        if (hasCreated) {
            if (ListUtils.isListValued(list)) {
                boolean b=false;
                if (mLLManager!=null){
                    b=mLLManager.findFirstCompletelyVisibleItemPosition()==0;
                }
                if (mAdapter != null) {
                    mAdapter.addDatas(list);
                    int count = mAdapter.getItemCount();
                    if (count > 0) {
                        mRecyclerView.smoothScrollToPosition(count - 1);
                    }
                }
            }
        }
    }
}
